#include "stdafx.h"
#include "Entity.h"
#include "Scene.h"
#include "MapManager.h"
#include "gamemanager.h"
#include "ObjectManager.h"
#include "inputmanager.h"
#include "playstate.h"

sgObject * sgEntity::Creator()
{
    return new sgEntity;
}

bool sgEntity::m_creatorRegisted = CObjectManager::Instance().RegisteCreator(OBJ_ENTITY, sgEntity::Creator );

sgEntity::sgEntity()
{
    m_layer = eLayer_Entity;
    m_classType = OBJ_ENTITY;
}

sgEntity::~sgEntity()
{

}

bool sgEntity::Initialize()
{
    EntityEntry &e = this->GetEntry();
    e.sizex = 0;
    e.sizey = 0;
    return true;
}

void sgEntity::Update( int delta )
{
    m_animation.Update( delta );
    EntityEntry &entry = GetEntry();
    int halfsizex = entry.sizex/2;
    int halfsizey = entry.sizey/2;
    IRect r( m_position.x - halfsizex, m_position.y - halfsizey, m_position.x + entry.sizex - halfsizex, m_position.y + entry.sizey - halfsizey);
    const InputInfo &info = CInputManager::Instance().GetInputInfo();
    if( IntersectRect( info.MapAreaMouse, r ) )
    {
        CObjectManager::Instance().AddSelectedEntity( this );
       // CGameManager::Instance().SwitchState( CMenuState::Create() );
    }
}

void sgEntity::Render()
{
    EntityEntry &entry = GetEntry();
    int halfsizex = entry.sizex/2;
    int halfsizey = entry.sizey/2;
    IRect r( m_position.x - halfsizex, m_position.y - halfsizey, m_position.x + entry.sizex - halfsizex, m_position.y + entry.sizey - halfsizey);
    CMapManager::Instance().ConvertToScaledCoord( r );
	m_animation.Render( r.x1 - gc.screenrect.x1, r.y1 - gc.screenrect.y1, r.Width(), r.Height(), m_layer );
}

IPoint	& sgEntity::GetPosition()
{
	return m_position;
}

void sgEntity::SetPosition( IPoint &point )
{
	m_position = point;
}

void sgEntity::Serialize( CSerialize& s )
{
    sgObject::Serialize(s);
    EntityEntry &e = this->GetEntry();
    s&MAKE_PAIR(e.name,"name");
    s&MAKE_PAIR(e.animName,"animName");
    s&MAKE_PAIR(m_position.x,"posx");
    s&MAKE_PAIR(m_position.y,"posy");
    s&MAKE_PAIR(e.sizex,"width");
    s&MAKE_PAIR(e.sizey,"height");
    s&MAKE_PAIR(e.type,"type");
}

void sgEntity::ProcessMessage( sgMessage *msg )
{
    return sgObject::ProcessMessage( msg );
}

sgEntity * sgEntity::Clone()
{
    sgEntity *ret = new sgEntity;
    ret->m_entry = m_entry;
    ret->Initialize();
    return ret;
}

EntityEntry & sgEntity::GetEntry()
{
    return m_entry;
}
